from flask import Flask, request, make_response, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager
from flask_cors import CORS
import os
import time
import logging
import sys
from dotenv import load_dotenv
from models.models import db

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 加载环境变量
load_dotenv()

# 获取数据库连接信息
db_host = os.getenv('DB_HOST', 'localhost')
db_user = os.getenv('DB_USER', 'root')
db_password = os.getenv('DB_PASSWORD', 'root')
db_name = os.getenv('DB_NAME', 'audio_recording_db')

# 创建应用
app = Flask(__name__)

# 配置应用
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'dev_secret_key')
app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET_KEY', 'dev_jwt_secret_key')
app.config['SQLALCHEMY_DATABASE_URI'] = f'mysql+pymysql://{db_user}:{db_password}@{db_host}:3306/{db_name}'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
    'pool_pre_ping': True,
    'pool_recycle': 3600,
    'connect_args': {
        'charset': 'utf8mb4'
    }
}
app.config['UPLOAD_FOLDER'] = os.path.join(os.path.dirname(__file__), 'storage', 'recordings')

logger.info(f"数据库连接: {db_host}:{db_name}")

# 确保上传文件夹存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

# 初始化扩展
db.init_app(app)
jwt = JWTManager(app)
CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True)

# 注册蓝图
from routes.auth import auth_bp
from routes.sentences import sentences_bp
from routes.recordings import recordings_bp
from routes.admin import admin_bp

app.register_blueprint(auth_bp, url_prefix='/api/auth')
app.register_blueprint(sentences_bp, url_prefix='/api/sentences')
app.register_blueprint(recordings_bp, url_prefix='/api/recordings')
app.register_blueprint(admin_bp, url_prefix='/api/admin')

# 简化的数据库初始化函数
def init_database():
    max_retries = 30
    for attempt in range(max_retries):
        try:
            logger.info(f"尝试连接数据库 (尝试 {attempt+1}/{max_retries})...")
            
            # 测试数据库连接
            with app.app_context():
                with db.engine.connect() as connection:
                    connection.execute(db.text('SELECT 1'))
                logger.info("数据库连接测试成功")
                
                # 创建表
                db.create_all()
                logger.info("数据库表创建成功")
                return True
                
        except Exception as e:
            logger.error(f"数据库连接失败 (尝试 {attempt+1}/{max_retries}): {e}")
            if attempt < max_retries - 1:
                time.sleep(2)
            else:
                logger.error("达到最大重试次数，数据库连接失败")
    return False

@app.errorhandler(Exception)
def handle_exception(e):
    logger.error(f"未处理的异常: {str(e)}", exc_info=True)
    return jsonify({
        "code": 500,
        "message": f"服务器错误: {str(e)}",
        "data": None
    }), 500

@app.route('/')
def hello_world():
    return 'Audio Recording System API'

if __name__ == '__main__':
    if len(sys.argv) > 1 and sys.argv[1] == 'init_db':
        with app.app_context():
            success = init_database()
            if not success:
                sys.exit(1)
        sys.exit(0)
    
    # 正常启动时初始化数据库
    with app.app_context():
        init_database()
    
    app.run(debug=True, host='0.0.0.0', port=5000)
